package com.gf.controller.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.gf.bean.Orderr;
import com.gf.service.impl.OrderrServiceImpl;
import com.gf.utils.Const;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/*
* 这是购物车模态框的下单按钮点击后处理下单的servlet
* */

@WebServlet(name = "order",urlPatterns = "/order")
public class OrderServlet extends HttpServlet {

        static OrderrServiceImpl orderimpl = null;
        static {
                orderimpl=new OrderrServiceImpl();
        }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        int userid =(int) request.getSession().getAttribute("userid");
        //获取到当前登陆的userid
        String remark = request.getParameter("remark");
        //再获取到传入的备注内容
        HashMap<String, Integer> shoppingcart = (HashMap<String, Integer>) request.getSession().getAttribute("shoppingcart");
        //获取到session中的购物车对象
        JSONObject backjson = new JSONObject();
        //新建json对象
        if (shoppingcart==null||shoppingcart.isEmpty()){
                //判断购物车是不是空的或者null是的话直接输出错误内容
                response.setStatus(300);
                backjson.put("status", 300);
                backjson.put("message",Const.GETORDER_FAIL);
        }else{
                Set<Map.Entry<String, Integer>> entries = shoppingcart.entrySet();
                Date date = new Date();
                String uuid = Const.UUID();

                for (Map.Entry<String, Integer> entry : entries) {
                        Orderr order = new Orderr(uuid,userid, Integer.valueOf(entry.getKey()), entry.getValue(), remark, date);
                        orderimpl.insert(order);
                }
                response.setStatus(200);
                backjson.put("status", 200);
                backjson.put("message","下单成功");
                backjson.put("data",uuid);
                request.getSession().setAttribute("shoppingcart",null);

        }
        out.println(JSON.toJSON(backjson));
        out.flush();
        out.close();


}
        }
